<?php
namespace app\article\model;

use think\Model;
use think\Db;

class Category extends Model {

//将$son_id下的树移动到$parent_id;
    function moveTo($son_id, $parent_id) {
        Db::table($this->getTable().'_move_to')->insert(array('son_id'=>$son_id,"parent_id"=>$parent_id));
        $re=$this->isInSameTree($son_id, $parent_id);

        if($re&&$parent_id){
            return false;
        }
        if($son_id==$parent_id){
            return false;
        }
        DB::startTrans();
        try {
            return true;
            $parent_id = intval($parent_id);
            $son_id = intval($son_id);
        } catch (Exception $e) {
            // 回滚事务
            DB::rollback();
            exception($e);
        }
        return FALSE;
    }
    //是否包含（防止循环）
    function isInSameTree($id1, $id2) {
        $son_ids = Db::query("SELECT * FROM  " . $this->getTable() . " where parent_id=$id1 AND id=$id2 ");
        return $son_ids;
    }

    /** parent_id父
     * son_id子
     *
     * */
//获取上面一层
    function getAParent($id, $length = 1) {
        $parent_ids = Db::query("SELECT * FROM  " . $this->getTable() . " where id=" . $id );
        if ($parent_ids && $parent_ids[0]) {
            return $parent_ids[0];
        } else {
            return FALSE;
        }
    }

}	